package com.muy.redis.common.tree.actions;

import com.intellij.icons.AllIcons;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ReadAction;
import com.intellij.util.concurrency.NonUrgentExecutor;
import com.muy.redis.common.tree.MTTreeCell;
import com.muy.redis.common.tree.TreeCellEventExeContext;
import com.muy.redis.common.tree.TreeCellEventHandle;
import com.muy.redis.common.tree.TreePanelMark;
import com.muy.redis.utils.JTreeUtils;
import com.muy.redis.view.component.MrRedisEditorJpanelLeft;
import com.muy.redis.view.window.redis.tree.MTTreeCellMrRedisKey;

import javax.swing.tree.DefaultMutableTreeNode;
import java.util.concurrent.CompletableFuture;

/**
 * @Author jiyanghuang
 * @Date 2023/9/28 22:28
 */
public class MrRedisReloadKeyValueAction extends AbstractMTTreeCellSelectTreeAction{

    private TreePanelMark treePanelMark;

    public MrRedisReloadKeyValueAction(TreePanelMark treePanelMark) {
        super("Reload value", "Reload value", AllIcons.Actions.Refresh, treePanelMark);
        this.treePanelMark = treePanelMark;
    }

    public MrRedisReloadKeyValueAction(TreePanelMark treePanelMark, String title, String desc) {
        super(title, desc, AllIcons.Actions.BuildAutoReloadChanges, treePanelMark);
    }

    @Override
    public void handleSelectTree(DefaultMutableTreeNode mutableTreeNode, MTTreeCell mtTreeCell) {
        MrRedisEditorJpanelLeft mrRedisEditorJpanelLeft = (MrRedisEditorJpanelLeft)treePanelMark;
        MTTreeCellMrRedisKey mtTreeCellMrRedisKey = (MTTreeCellMrRedisKey)mtTreeCell;

        JTreeUtils.processLoading(TreeCellEventExeContext.of(mrRedisEditorJpanelLeft.jTree(), mutableTreeNode), new TreeCellEventHandle<Void>() {

            @Override
            public void process(TreeCellEventExeContext exeContext, CompletableFuture<Void> cf) throws Exception {
                ReadAction.nonBlocking(() -> {
                    mtTreeCellMrRedisKey.reloadValue();
                    return null;
                }).finishOnUiThread(ModalityState.defaultModalityState(), p -> {
                    cf.complete(null);
                }).inSmartMode(mrRedisEditorJpanelLeft.getProject()).submit(NonUrgentExecutor.getInstance());
            }
        });
    }
}
